#include "union.h"
#include "scene_logic.h"
#include "../share/time_module.h"
#include "scene_event.h"
#include "union_module.h"
#include "../share/tplmgr.h"
#include "Fixed1024.h"
#include "MapSlot.h"
#include "script_define.h"
#include "GameServer.h"
#include "../share/MessageDef.h"
#include "../share/proxyclient_service.h"
#include "../share/GameHostManager.h"
#include "../share/sql/mysql_connection.h"
#include "../share/sql/mysql_resultset.h"
#include "MonsterCacheData.h"
#include "activity_module.h"
#include "mail_module.h"
#include "ManagerHelper.h"


const int32_t GUILD_BUILDING_COUNT = 4;
const int32_t GUILD_REDPACKET_DELETE_TIME = 86400;	// 历史红包保留时间 1天

CGuildMember::CGuildMember() : playerid_(0), join_time_(0), title_(0), total_donation_(0)
{
	playerid_ = 0;
	join_time_ = 0;
	title_ = 0;
	total_donation_ = 0;
	week_donation_ = 0;
	day_donation_ = 0;
	gold_donationcount_ = 0;
	diamod_donationcount_ = 0;
	ticket_donationcount_ = 0;
	alcohol_id = 0;
	alcohol_count = 0;
	alcohol_expire = 0;
	donationtime_ = 0;
}

CGuildMember::~CGuildMember()
{
}

void CGuildMember::OnNewDay()
{
	gold_donationcount_ = 0;
	diamod_donationcount_ = 0;
	ticket_donationcount_ = 0;
	day_donation_ = 0;

	// 酒buff 一天后刷新
	//if ((CUR_SEC - alcohol_expire) > 86400) {
		alcohol_count = 0;
		//alcohol_id = 0;
	//}
}

void CGuildMember::OnNewWeekDay()
{
	week_donation_ = 0;
}

CGuildBoss::CGuildBoss(CGuild& guild):guild_(guild)
{
	Clear();
}

CGuildBoss::~CGuildBoss()
{

}

void CGuildBoss::Clear()
{
	boss_id_ = 0;
	boss_max_hp_ = 0;
	boss_cur_hp_ = 0;
	boss_lv_ = 0;
	player_damage_map_.clear();
}

bool CGuildBoss::LoadFromJson(Json::Value& boss_json)
{
	boss_id_ = boss_json["bossid"].asInt();
	boss_lv_ = boss_json["bosslv"].asInt();
	boss_max_hp_ = boss_json["maxhp"].asDouble();
	boss_cur_hp_ = boss_json["curhp"].asDouble();
	Json::Value ranklist = boss_json["ranklist"];
	for ( int32_t i = 0; i < ranklist.size(); ++i )
	{
		Json::Value onerank = ranklist[i];
		std::pair<int32_t, int64_t> onepair;
		onepair.first = onerank["playerid"].asInt();
		onepair.second = onerank["damage"].asDouble();
		player_damage_rank_.push_back(onepair);
	}
	return true;
}

bool CGuildBoss::SaveToJson(Json::Value& boss_json)
{
	boss_json["bossid"] = boss_id_;
	boss_json["bosslv"] = boss_lv_;
	boss_json["maxhp"] = (double)boss_max_hp_;
	boss_json["curhp"] = (double)boss_cur_hp_;
	Json::Value ranklist;
	for (TPlayerDamageRankVec::iterator it = player_damage_rank_.begin(); it != player_damage_rank_.end(); ++it )
	{
		Json::Value onerank;
		onerank["playerid"] = (int32_t)it->first;
		onerank["damage"] = (double)it->second;
		ranklist.append(onerank);
	}
	boss_json["ranklist"] = ranklist;
	return true;
}


void CGuildBoss::PlayerEnterBoss(int32_t playerid)
{
	TPlayerDamageMap::iterator it = player_damage_map_.find(playerid);
	if ( it == player_damage_map_.end() )
	{
		player_damage_map_[playerid] = 0;
	}
	TPlayerUpdateDamageTimeMap::iterator iter = player_update_map_.find(playerid);
	if ( iter == player_update_map_.end() )
	{
		player_update_map_[playerid] = 0;
	}
}

void CGuildBoss::AddPlayerDamage(int32_t playerid, int32_t damage, bool isdie)
{
	TPlayerUpdateDamageTimeMap::iterator iter = player_update_map_.find(playerid);
	if (iter == player_update_map_.end())
	{
		return;
	}

	// 这里还是有可能有问题，玩家每次都把isdie赋值为true，那么就可能作弊了，可以记录一下一个玩家一场战斗只能发一次isdie
	int32_t curtime = CUR_SEC;
	if (!isdie)
	{
		if (iter->second != 0 && curtime < iter->second + 1)
		{
			LOG_WARN("default", "player[%d] lasttime[%d],now[%d] update damage[%d] too less time", playerid, iter->second, curtime, damage);
			return;
		}
	}
	
	
	TPlayerDamageMap::iterator it = player_damage_map_.find(playerid);
	if ( it == player_damage_map_.end() )
	{
		return;
	}
	it->second += damage;
	iter->second = curtime;

	BossReduceHp(playerid, damage);
}

void CGuildBoss::BossReduceHp(int32_t playerid, int32_t damage)
{
	if ( isDie() )
	{
		LOG_INFO("default", "boss is die!");
		return;
	}
	if (boss_cur_hp_ >= damage)
	{
		boss_cur_hp_ -= damage;
	}
	else
	{
		boss_cur_hp_ = 0;
	}

	if ( isDie() )
	{
		// 触发结算通知
		guild_.BossDieNotify();
		guild_.onBossEnd(true);
		guild_.KillBoss(playerid);

		// 计算首杀
		CGuildManager::GetInstance().CalcFirstKill(guild_, boss_id_, boss_lv_, playerid);
	}
}

bool cmpDamageRank(const std::pair<int32_t, int64_t>& lplayer, const std::pair<int32_t, int64_t>& rplayer)
{
	return lplayer.second > rplayer.second;
}

void CGuildBoss::FillDamageRank(Json::Value& damagerank_json)
{
	int32_t rank = 0;
	for (std::vector< std::pair<int32_t, int64_t> >::iterator it = player_damage_rank_.begin(); it != player_damage_rank_.end(); ++it )
	{
		CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(it->first);
		if ( playerinfo == NULL )
		{
			continue;
		}
		if ( it->second <= 0 )
		{
			continue;
		}
		Json::Value oneRank;
		oneRank["rank"] = ++rank;
		oneRank["damage"] = (double)(it->second);
		oneRank["playerId"] = (int32_t)(it->first);
		oneRank["name"] = playerinfo->get_name();

		damagerank_json.append(oneRank);
	}
}

void CGuildBoss::CalcDamageRank()
{
	player_damage_rank_.clear();
	std::vector< std::pair<int32_t, int64_t> > damage_vector(player_damage_map_.begin(), player_damage_map_.end());
	std::sort(damage_vector.begin(), damage_vector.end(), cmpDamageRank);
	player_damage_rank_.assign(damage_vector.begin(), damage_vector.end());
}

void CGuildBoss::StartBoss()
{
	player_damage_map_.clear();
	player_damage_rank_.clear();
	player_update_map_.clear();
	if (boss_cur_hp_ == 0)
	{
		boss_lv_ += 1;
	}
	const CUnionBossCfg& boss_cfg = CTPLManager::GetInstance().GetUnionBossInfo();
	const CUnionBossLv* bosslv = boss_cfg.Getbossinfo(boss_lv_);
	if ( bosslv == NULL )
	{
		LOG_ERROR("default", "start boss err bosslv config is null");
		return;
	}
	boss_id_ = bosslv->monsterid();
	MonsterInfo* bossinfo = MonsterCacheData::GetInstance().GetData(boss_id_);
	if ( bossinfo == NULL )
	{
		LOG_ERROR("default", "start boss err MonsterInfo[%d] is null", boss_id());
		return;
	}
	//boss_max_hp_ = bossinfo->mHp + bossinfo->mLvHp * boss_lv_;
	boss_max_hp_ = 500000;
	boss_cur_hp_ = boss_max_hp_;
}

bool CGuildBoss::isDie()
{
	return boss_cur_hp_ <= 0; 
}

int32_t CGuildBoss::GetFirstRankPlayer()
{
	if ( player_damage_rank_.size() == 0)
	{
		return 0;
	}
	return player_damage_rank_.front().first;
}

CGuild::CGuild() :guild_boss_(*this)
{
	Clear();
}

CGuild::~CGuild()
{
	Clear();
}

int32_t CGuild::Clear()
{
	member_map_.clear();
	apply_map_.clear();
	m_unionRepacket_map_.clear();
	guild_id_ = 0;
	guild_level_ = 0;
	guild_exp_ = 0;
	create_time_ = 0;
	guild_name_.clear();
	declaration_.clear();
	today_donation_ = 0;
	is_dissovled_ = false;
	dissovled_time_ = 0;
	last_save_time_ = 0;
	chairman_player_id_ = 0;
	create_player_id_ = 0;
	guild_icon_ = "";
	min_limit_lv_ = 0;
	auto_join_ = 0;
	return ::common::SUCCEED;
}



bool CGuild::InApplyList(int32_t player_id) const
{
	TGuildApplyMap::const_iterator it = apply_map_.find(player_id);
	if (it == apply_map_.end())
	{
		return false;
	}
	return true;
}

void CGuild::FillApplyList(Json::Value& item)
{
	item.clear();
	for (TGuildApplyMap::iterator it = apply_map_.begin(); it != apply_map_.end(); ++it)
	{
		CPlayerInfo* player = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(it->first);
		if (player == NULL)
		{
			continue;
		}
		Json::Value oneplayer;
		oneplayer.clear();
		oneplayer["account"] = player->get_accountId();
		oneplayer["playerId"] = player->get_playerId();
		oneplayer["name"] = player->get_name();
		oneplayer["level"] = player->get_level();
		oneplayer["afc"] = player->get_afc();
		oneplayer["heroId"] = player->get_heroid();
		oneplayer["usrPosId"] = player->get_playerId();
		oneplayer["ct"] = it->second;
		item.append(oneplayer);
	}
}

void CGuild::FillMemberList(Json::Value& item)
{
	item.clear();
	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
	{
		CGuildMember& guildmember = it->second;
		CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(guildmember.player_id());
		if (playerinfo == NULL)
		{
			continue;
		}
		Json::Value oneplayer;
		oneplayer["id"] = playerinfo->get_playerId();
		oneplayer["ac"] = playerinfo->get_accountId();
		oneplayer["nm"] = playerinfo->get_name();
		oneplayer["ui"] = playerinfo->get_union_id();
		oneplayer["up"] = playerinfo->union_pos();
		oneplayer["afc"] = playerinfo->get_afc();
		oneplayer["pt"] = playerinfo->get_heroid();
		oneplayer["sd"] = playerinfo->get_heroSkinId();
		oneplayer["lv"] = playerinfo->get_level();
		oneplayer["vp"] = playerinfo->get_vip();
		oneplayer["wdn"] = guildmember.week_donation();
		oneplayer["adn"] = guildmember.total_contribution();
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(it->first);
		if (player == NULL)
		{
			oneplayer["ol"] = 0;
		}
		else
		{
			oneplayer["ol"] = 1;
		}
		oneplayer["logout"] = playerinfo->last_logout_time();

		item.append(oneplayer);
	}
}

void CGuild::FillMemberList2(Json::Value& item)
{
	item.clear();
	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
	{
		CGuildMember& guildmember = it->second;
		CPlayerInfo* player = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(guildmember.player_id());
		if (player == NULL)
		{
			continue;
		}
		Json::Value oneplayer;
		oneplayer["playerId"] = player->get_playerId();
		oneplayer["name"] = player->get_name();
		oneplayer["unionPosition"] = player->union_pos();
		oneplayer["heroId"] = player->get_heroid();
		oneplayer["heroSkinId"] = player->get_heroSkinId();
		oneplayer["level"] = player->get_level();
		item.append(oneplayer);
	}
}


void CGuild::FillonlineMemberList(Json::Value& item)
{
	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
	{
		CGuildMember& guildmember = it->second;
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(guildmember.player_id());
		if ( player != NULL )
		{
			Json::Value playerinfo;
			player->FillBaseInfoToJson(playerinfo);
			item.append(playerinfo);
		}
	}
}

void CGuild::FillGuildLog(Json::Value& item)
{
	item.clear();
	for (TGuildLogList::iterator it = guild_log_.begin(); it != guild_log_.end(); ++it )
	{
		CGuildLog& guildlog = *it;
		Json::Value log;
		log["op_playerid"] = guildlog.op_playerid;
		log["op_name"] = guildlog.op_name;
		log["op_type"] = guildlog.op_type;
		log["beop_playerid"] = guildlog.beop_playerid;
		log["beop_name"] = guildlog.beop_name;
		log["op_time"] = guildlog.op_time;
		log["param"] = guildlog.param;

		item.append(log);
	}
}

int32_t CGuild::AddApply(int32_t player_id)
{
	apply_map_[player_id] = CUR_SEC;
	return ::common::SUCCEED;
}

void CGuild::DeleteApply(int32_t playerid)
{
	TGuildApplyMap::iterator it = apply_map_.find(playerid);
	if ( it != apply_map_.end() )
	{
		apply_map_.erase(it);
	}
}

int32_t CGuild::LeaveGuild(int32_t playerid)
{
	member_map_.erase(playerid);
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(playerid);
	if ( playerinfo != NULL )
	{
		playerinfo->PlayerGuild().set_leave_guild_time(CUR_SEC);
		CPlayerInfoMgr::GetInstance().PlayerChanged(playerid);
	}
	return ::common::SUCCEED;
}

// 会长操作
int32_t CGuild::AppointTitle(CGuildMember& handlers, int32_t destId, int32_t title)
{
	CGuildMember* member = GetMember(destId);
	if (NULL == member)
	{
		return ::common::ERR_NOT_YOUR_UNION_MEMBER;
	}
	if ( title == E_GUILD_TITLE_CHAIRMAN )
	{
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(destId);
		if ( player == NULL )
		{
			return ::common::ERR_GUILD_MEMBER_MUST_ONLINE;
		}
		member->set_title(E_GUILD_TITLE_CHAIRMAN);
		handlers.set_title(E_GUILD_TITLE_MEMBER);

		//player_union_data_change(handlers.player_id(), guild_id_, guild_name_, E_GUILD_TITLE_MEMBER, E_PERMISSION_CHANGE);
		CUnionModule::GetInstance().OnPlayerUnionDataChange(handlers.player_id(), guild_id_, guild_name_, E_GUILD_TITLE_MEMBER, E_PERMISSION_CHANGE);
		//player_union_data_change(destId, guild_id_, guild_name_, E_GUILD_TITLE_CHAIRMAN, E_PERMISSION_CHANGE);
		CUnionModule::GetInstance().OnPlayerUnionDataChange(destId, guild_id_, guild_name_, E_GUILD_TITLE_CHAIRMAN, E_PERMISSION_CHANGE);
	}
	else if ( title == E_GUILD_TITLE_VICE_CHAIRMAN)
	{
		// 会长任命副会长的时候，将原来副会长解除职务
		CGuildMember* vice_man = GetViceChairman();
		if ( vice_man != NULL )
		{
			vice_man->set_title(E_GUILD_TITLE_MEMBER);
			CUnionModule::GetInstance().OnPlayerUnionDataChange(vice_man->player_id(), guild_id_, guild_name_, E_GUILD_TITLE_MEMBER, E_PERMISSION_CHANGE);
		}
		member->set_title(E_GUILD_TITLE_VICE_CHAIRMAN);

		//player_union_data_change(destId, guild_id_, guild_name_, E_GUILD_TITLE_CHAIRMAN, E_PERMISSION_CHANGE);
		CUnionModule::GetInstance().OnPlayerUnionDataChange(destId, guild_id_, guild_name_, E_GUILD_TITLE_VICE_CHAIRMAN, E_PERMISSION_CHANGE);
	}
	else
	{
		member->set_title(E_GUILD_TITLE_MEMBER);

		//player_union_data_change(destId, guild_id_, guild_name_, E_GUILD_TITLE_CHAIRMAN, E_PERMISSION_CHANGE);
		CUnionModule::GetInstance().OnPlayerUnionDataChange(destId, guild_id_, guild_name_, E_GUILD_TITLE_MEMBER, E_PERMISSION_CHANGE);
	}
	return ::common::SUCCEED;
}

void CGuild::AddGuildLog(int32_t op_playerid, int32_t beopplayerid, int32_t optype, int32_t param)
{
	CGuildLog guildlog;
	guildlog.op_playerid = op_playerid;
	CPlayerInfo* op_playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(op_playerid);
	if ( op_playerinfo == NULL )
	{
		return;
	}
	guildlog.op_name = op_playerinfo->get_name();
	guildlog.beop_playerid = beopplayerid;
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(beopplayerid);
	if (playerinfo == NULL)
	{
		return;
	}
	guildlog.beop_name = playerinfo->get_name();
	guildlog.op_type = optype;
	guildlog.op_time = CUR_SEC;
	guildlog.param = param;

	if ( guild_log_.size() < 40 )
	{
		guild_log_.push_back(guildlog);
	}
	else
	{
		guild_log_.pop_front();
		guild_log_.push_back(guildlog);
	}
}

int32_t CGuild::GoldDonation(Player& player)
{
	CGuildMember* guildMember = GetMember(player.GetPlayerId());
	if (guildMember == NULL)
	{
		return ::common::ERR_NOT_JOINED_UNION;
	}
	const CUnionLvCfg* union_lv = CTPLManager::GetInstance().GetUnionCfgByLevel(guild_level_);
	if (union_lv == NULL)
	{
		return ::common::ERR_GOT_UNION_INFO_FAIL;
	}
	UnionDonateInfo kUnionDonateInfo = UnionDonateTableMgrPtr->GetUnionDonateInfoById((guild_level_ - 1) * 3 + EGoldDonation);
	if (guildMember->gold_donationcount() >= kUnionDonateInfo.m_second)
	{
		return ::common::ERR_UNION_CONTRIBUTION_TO_LIMIT;
	}
	// 判断消耗
	if ( player.GetCurrency(Fixed1024::CURRENCY_GOLD) < kUnionDonateInfo.m_consumeItemCount)
	{
		return ::common::ERR_GUILD_NOT_ENOUGH_GOLD;
	}
	// 先消耗
	int32_t ret = player.ChangeNumber(Fixed1024::CURRENCY_GOLD, kUnionDonateInfo.m_consumeItemCount);
	if (ret != ::common::SUCCEED)
	{
		LOG_ERROR("default","change number err player[%d] ret[%d]", player.GetPlayerId(), ret);
		return ::common::ERR_GUILD_NOT_ENOUGH_GOLD;
	}
	guildMember->set_donationtime(CUR_SEC);
	guildMember->set_gold_donationcount(guildMember->gold_donationcount() + 1);
	int32_t addexp = kUnionDonateInfo.m_contribution;
	set_guild_exp(guild_exp_ + addexp);
	guildMember->add_donation(kUnionDonateInfo.m_contribution);
	return ::common::SUCCEED;
}

int32_t CGuild::DiamonDonation(Player& player)
{
	CGuildMember* guildMember = GetMember(player.GetPlayerId());
	if (guildMember == NULL)
	{
		return ::common::ERR_NOT_JOINED_UNION;
	}
	const CUnionLvCfg* union_lv = CTPLManager::GetInstance().GetUnionCfgByLevel(guild_level_);
	if (union_lv == NULL)
	{
		return ::common::ERR_GOT_UNION_INFO_FAIL;
	}
	UnionDonateInfo kUnionDonateInfo = UnionDonateTableMgrPtr->GetUnionDonateInfoById((guild_level_ - 1) * 3 + EDiamondDonation);
	if (guildMember->diamod_donationcount() >= kUnionDonateInfo.m_second)
	{
		return ::common::ERR_UNION_CONTRIBUTION_TO_LIMIT;
	}
	// 判断消耗
	if (player.GetCurrency(Fixed1024::CURRENCY_DIAMOND) < kUnionDonateInfo.m_consumeItemCount)
	{
		return ::common::ERR_GUILD_NOT_ENOUGH_DIAMOND;
	}
	// 先消耗
	int32_t ret = player.ChangeNumber(Fixed1024::CURRENCY_DIAMOND, kUnionDonateInfo.m_consumeItemCount);
	if (ret != ::common::SUCCEED)
	{
		LOG_ERROR("default","change number err player[%d] ret[%d]", player.GetPlayerId(), ret);
		return ::common::ERR_GUILD_NOT_ENOUGH_DIAMOND;
	}
	guildMember->set_donationtime(CUR_SEC);
	guildMember->set_diamod_donationcount(guildMember->diamod_donationcount() + 1);
	int32_t addexp = kUnionDonateInfo.m_contribution;
	set_guild_exp(guild_exp_ + addexp);
	guildMember->add_donation(kUnionDonateInfo.m_contribution);
	return ::common::SUCCEED;
}

int32_t CGuild::TicketDonation(Player& player)
{
	CGuildMember* guildMember = GetMember(player.GetPlayerId());
	if (guildMember == NULL)
	{
		return ::common::ERR_NOT_JOINED_UNION;
	}
	const CUnionLvCfg* union_lv = CTPLManager::GetInstance().GetUnionCfgByLevel(guild_level_);
	if (union_lv == NULL)
	{
		return ::common::ERR_GOT_UNION_INFO_FAIL;
	}
	UnionDonateInfo kUnionDonateInfo = UnionDonateTableMgrPtr->GetUnionDonateInfoById((guild_level_ - 1) * 3 + ETicketDonation);
	if (guildMember->ticket_donationcount() >= kUnionDonateInfo.m_second)
	{
		return ::common::ERR_UNION_CONTRIBUTION_TO_LIMIT;
	}
	// 判断消耗
	if (player.GetCurrency(Fixed1024::CURRENCY_TICKET) < kUnionDonateInfo.m_consumeItemCount)
	{
		return ::common::ERR_GUILD_UNION_SENDREPACKET_DIAMOND_ERR;
	}
	// 先消耗
	int32_t ret = player.ChangeNumber(Fixed1024::CURRENCY_TICKET, kUnionDonateInfo.m_consumeItemCount);
	if (ret != ::common::SUCCEED)
	{
		LOG_ERROR("default", "change number err player[%d] ret[%d]", player.GetPlayerId(), ret);
		return ::common::ERR_GUILD_UNION_SENDREPACKET_DIAMOND_ERR;
	}
	guildMember->set_donationtime(CUR_SEC);
	guildMember->set_ticket_donationcount(guildMember->ticket_donationcount() + 1);
	int32_t addexp = kUnionDonateInfo.m_contribution;
	set_guild_exp(guild_exp_ + addexp);
	guildMember->add_donation(kUnionDonateInfo.m_contribution);
	return ::common::SUCCEED;
}

int32_t CGuild::LevelUp(Player& player)
{
	const CUnionLvCfg* union_lv = CTPLManager::GetInstance().GetUnionCfgByLevel(guild_level_);
	if (union_lv == NULL)
	{
		return ::common::ERR_GOT_UNION_INFO_FAIL;
	}

	if ( guild_exp_ < union_lv->guild_exp )
	{
		return ::common::ERR_NOT_ENOUGH_UNION_EXP;
	}

	guild_exp_ = guild_exp_ - union_lv->guild_exp;
	guild_level_++;

	return ::common::SUCCEED;
}

void CGuild::OnNewDay()
{
	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it )
	{
		CGuildMember& member = it->second;
		member.OnNewDay();
	}
}

void CGuild::OnNewWeek()
{
	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
	{
		CGuildMember& member = it->second;
		member.OnNewWeekDay();
	}
}

bool CGuild::LoadFromJson(const Json::Value& guild_json)
{
	guild_id_ = guild_json["guildid"].asInt();
	guild_name_ = guild_json["guildname"].asString();
	create_player_id_ = guild_json["createid"].asInt();
	chairman_player_id_ = guild_json["chairid"].asInt();
	guild_icon_ = guild_json["icon"].asString();
	guild_level_ = guild_json["guildlv"].asInt();
	guild_exp_ = guild_json["guildexp"].asInt();
	create_time_ = guild_json["createtime"].asInt();
	is_dissovled_ = guild_json["dissovled"].asInt();
	dissovled_time_ = guild_json["dissovledtime"].asInt();

	std::string exdata = guild_json["exdata"].asString();
	Json::Value exdata_json;
	bool ret = JsonReader(exdata, exdata_json);
	if ( ret == false )
	{
		LOG_ERROR("default","load guild apply info err guildid:%d", guild_id_);
		return false;
	}
	LoadExDataFromJson(exdata_json);

	std::string apply = guild_json["apply"].asString();
	Json::Value apply_json;
	ret = JsonReader(apply, apply_json);
	if ( ret == false )
	{
		LOG_ERROR("default","load guild apply info err guildid:%d", guild_id_);
		return false;
	}
	LoadApplyFromJson(apply_json);

	std::string member = guild_json["member"].asString();
	Json::Value member_json;
	ret = JsonReader(member, member_json);
	if ( ret == false )
	{
		LOG_ERROR("default","load guild apply info err guildid:%d", guild_id_);
		return false;
	}
	LoadMemberFromJson(member_json);

	std::string redpacket = guild_json["redpacket"].asString();
	Json::Value redpacket_json;
	ret = JsonReader(redpacket, redpacket_json);
	if (ret == false)
	{
		LOG_ERROR("default", "load guild redpacket info err guildid:%d", guild_id_);
		return false;
	}
	LoadRedPacketFromJson(redpacket_json);
	return true;
}

bool CGuild::SaveToJson(Json::Value& guild_json)
{
	guild_json["guildid"] = guild_id_;
	guild_json["guildname"] = guild_name_;
	guild_json["createid"] = create_player_id_;
	guild_json["chairid"] = chairman_player_id_;
	guild_json["icon"] = guild_icon_;
	guild_json["guildlv"] = guild_level_;
	guild_json["guildexp"] = guild_exp_;
	guild_json["createtime"] = create_time_;
	guild_json["dissovled"] = is_dissovled_ ? 1:0;
	guild_json["dissovledtime"] = dissovled_time_;
	
	Json::Value exjson;
	if (!SaveGuildExToJson(exjson))
	{
		LOG_ERROR("default","SaveGuildExToJson err! guildid:%d", guild_id_);
	}
	guild_json["exdata"] = exjson;

	Json::Value apply;
	if (!SaveApplyToJson(apply))
	{
		LOG_ERROR("default","SaveApplyToJson err! guildid:%d", guild_id_);
	}
	guild_json["apply"] = apply;
	
	Json::Value member;
	if (!SaveMemberToJson(member))
	{
		LOG_ERROR("default","SaveMemberToJson err! guildid:%d", guild_id_);
	}
	guild_json["member"] = member;

	Json::Value redpacket;
	if (!SaveGuildRedpacketToJson(redpacket))
	{
		LOG_ERROR("default", "SaveGuildRedpacketToJson err! guildid:%d", guild_id_);
	}
	guild_json["redpacket"] = redpacket;
	return true;
}

bool CGuild::SaveApplyToJson(Json::Value& applyjson)
{
	for (TGuildApplyMap::iterator it = apply_map_.begin(); it != apply_map_.end(); ++it)
	{
		Json::Value oneplayer;
		oneplayer.clear();
		oneplayer["playerId"] = it->first;
		oneplayer["applytime"] = it->second;
		applyjson.append(oneplayer);
	}
	return true;
}

bool CGuild::SaveMemberToJson(Json::Value& memberjson)
{
	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
	{
		CGuildMember& guildmember = it->second;
		Json::Value oneplayer;
		oneplayer.clear();
		oneplayer["playerId"] = guildmember.player_id();
		oneplayer["jointime"] = guildmember.join_time();
		oneplayer["title"] = guildmember.title();
		oneplayer["totaldon"] = guildmember.total_contribution();
		oneplayer["weekdon"] = guildmember.week_donation();
		oneplayer["daydon"] = guildmember.day_donation();
		oneplayer["gold"] = guildmember.gold_donationcount();
		oneplayer["diamod"] = guildmember.diamod_donationcount();
		oneplayer["ticket"] = guildmember.ticket_donationcount();
		oneplayer["alcohol_id"] = guildmember.get_alcohol_id();
		oneplayer["alcohol_count"] = guildmember.get_alcohol_count();
		oneplayer["alcohol_expire"] = guildmember.get_alcohol_expire();
		oneplayer["donationtime"] = guildmember.get_donationtime();
		memberjson.append(oneplayer);
	}
	return true;
}

bool CGuild::SaveGuildExToJson(Json::Value& exjson)
{
	Json::Value detail_json;
	detail_json["minlv"] = min_limit_lv_;
	detail_json["autojoin"] = auto_join_;

	Json::Value guild_log;
	FillGuildLog(guild_log);

	exjson["detail"] = detail_json;
	exjson["log"] = guild_log;

	Json::Value guild_boss;
	guild_boss_.SaveToJson(guild_boss);
	exjson["boss"] = guild_boss;
	return true;
}

bool CGuild::SaveGuildRedpacketToJson(Json::Value& rpjson)
{
	for (TCUnionRepacketMap::iterator it = m_unionRepacket_map_.begin(); it != m_unionRepacket_map_.end(); ++it)
	{
		CUnionRepacket& guild_repacket = it->second;

		Json::Value oneredpacket;
		oneredpacket["idx"] = guild_repacket.m_idx;
		oneredpacket["unionId"] = guild_repacket.m_unionId;
		oneredpacket["playerId"] = guild_repacket.m_playerId;
		oneredpacket["name"] = guild_repacket.m_name;
		oneredpacket["sendTime"] = guild_repacket.m_sendTime;
		oneredpacket["tId"] = guild_repacket.m_tId;
		oneredpacket["remainItemCount"] = guild_repacket.m_remainItemCount;
		oneredpacket["getCount"] = guild_repacket.m_getCount;
		oneredpacket["createTime"] = guild_repacket.m_createTime;

		Json::Value list_json;
		for (TUnionRepacketInfoMap::iterator it = guild_repacket.m_list.begin(); it != guild_repacket.m_list.end(); ++it)
		{
			Json::Value oneInfo;
			oneInfo["playerId"] = it->second.m_playerId;
			oneInfo["getTime"] = it->second.m_getTime;
			oneInfo["getnum"] = it->second.m_getnum;
			oneInfo["name"] = it->second.m_name;
			list_json.append(oneInfo);
		}
		oneredpacket["list"] = list_json;

		rpjson.append(oneredpacket);
	}
	
	return true;
}

bool CGuild::LoadApplyFromJson(Json::Value& applyjson)
{
	for ( int32_t i = 0; i < applyjson.size(); ++i )
	{
		int32_t playerId = applyjson[i]["playerId"].asInt();
		int32_t applytime = applyjson[i]["applytime"].asInt();
		apply_map_.insert(std::make_pair(playerId, applytime));
	}
	return true;
}

bool CGuild::LoadMemberFromJson(Json::Value& memberjson)
{
	for ( int32_t i = 0; i < memberjson.size(); ++i )
	{
		CGuildMember guildmember;
		int32_t playerId = memberjson[i]["playerId"].asInt();
		int32_t jointime = memberjson[i]["jointime"].asInt();
		int32_t title = memberjson[i]["title"].asInt();
		int32_t totaldon = memberjson[i]["totaldon"].asInt();
		int32_t weekdon = memberjson[i]["weekdon"].asInt();
		int32_t daydon = memberjson[i]["daydon"].asInt();
		int32_t gold = memberjson[i]["gold"].asInt();
		int32_t diamod = memberjson[i]["diamod"].asInt();
		int32_t ticket = memberjson[i]["ticket"].asInt();
		int32_t alcohol_id = memberjson[i]["alcohol_id"].asInt();
		int32_t alcohol_count = memberjson[i]["alcohol_count"].asInt();
		int32_t alcohol_expire = memberjson[i]["alcohol_expire"].asInt();
		int32_t donationtime = memberjson[i]["donationtime"].asInt();

		guildmember.set_player_id(playerId);
		guildmember.set_join_time(jointime);
		guildmember.set_title(title);
		guildmember.set_total_contribution(totaldon);
		guildmember.set_week_donation(weekdon);
		guildmember.set_day_donation(daydon);
		guildmember.set_gold_donationcount(gold);
		guildmember.set_diamod_donationcount(diamod);
		guildmember.set_ticket_donationcount(ticket);
		guildmember.set_alcohol_id(alcohol_id);
		guildmember.set_alcohol_count(alcohol_count);
		guildmember.set_alcohol_expire(alcohol_expire);
		guildmember.set_donationtime(donationtime);

		if (donationtime > 0)
		{
			time_t cur_sec = CUR_SEC;
			tm* update_tm = localtime(&cur_sec);
			time_t day_time = ::common::RebuildTime(update_tm, 50000);
			// 跨天
			if (cur_sec >= day_time && donationtime < day_time)
			{
				guildmember.OnNewDay();
			}
			update_tm = localtime(&cur_sec);
			day_time = ::common::RebuildTime(update_tm, 50000);
			int32_t week_day = update_tm->tm_wday;
			if (week_day == 0)
			{
				week_day = 7;
			}
			int32_t week_time = day_time - (week_day - 1) * 24 * 60 * 60;
			// 跨周
			if (cur_sec >= week_time && donationtime < week_time)
			{
				guildmember.OnNewWeekDay();
			}
		}

		member_map_.insert(std::make_pair(playerId, guildmember));
	}
	return true;
}

bool CGuild::LoadExDataFromJson(Json::Value& exjson)
{
	Json::Value detail_json = exjson["detail"];
	min_limit_lv_ = detail_json["minlv"].asInt();
	auto_join_ = detail_json["autojoin"].asInt();

	Json::Value guild_log = exjson["log"];
	for (int32_t i = 0;i < guild_log.size(); ++i)
	{
		Json::Value log = guild_log[i];
		CGuildLog glog;
		glog.op_playerid = log["op_playerid"].asInt();
		glog.op_name = log["op_name"].asString();
		glog.beop_name = log["beop_name"].asString();
		glog.beop_playerid = log["beop_playerid"].asInt();
		glog.op_time = log["op_time"].asInt();
		glog.op_type = log["op_type"].asInt();
		glog.param = log["param"].asInt();

		guild_log_.push_back(glog);
	}

	Json::Value guild_boss = exjson["boss"];
	guild_boss_.LoadFromJson(guild_boss);
	return true;
}

bool CGuild::LoadRedPacketFromJson(Json::Value& redpacketjson)
{
	for (int32_t i = 0; i < redpacketjson.size(); ++i)
	{
		CUnionRepacket kCUnionRepacket;
		kCUnionRepacket.m_idx = redpacketjson[i]["idx"].asInt();
		kCUnionRepacket.m_unionId = redpacketjson[i]["unionId"].asInt();
		kCUnionRepacket.m_playerId = redpacketjson[i]["playerId"].asInt();
		kCUnionRepacket.m_name = redpacketjson[i]["name"].asString();
		kCUnionRepacket.m_sendTime = redpacketjson[i]["sendTime"].asInt();
		kCUnionRepacket.m_tId = redpacketjson[i]["tId"].asInt();
		kCUnionRepacket.m_remainItemCount = redpacketjson[i]["remainItemCount"].asInt();
		kCUnionRepacket.m_getCount = redpacketjson[i]["getCount"].asInt();
		kCUnionRepacket.m_createTime = redpacketjson[i]["createTime"].asInt();
		Json::Value list_json = redpacketjson[i]["list"];
		for (int i = 0; i < list_json.size(); ++i )
		{
			CUnionRepacketInfo kCUnionRepacketInfo;
			kCUnionRepacketInfo.m_playerId = list_json[i]["playerId"].asInt();
			kCUnionRepacketInfo.m_getTime = list_json[i]["getTime"].asInt();
			kCUnionRepacketInfo.m_getnum = list_json[i]["getnum"].asInt();
			kCUnionRepacketInfo.m_name = list_json[i]["name"].asString();
			kCUnionRepacket.m_list[kCUnionRepacketInfo.m_playerId] = kCUnionRepacketInfo;
		}

		UpdateRedpacket(kCUnionRepacket);

		if (CGuildManager::GetInstance().GetRedpacketIdMax() < kCUnionRepacket.m_idx)
		{
			CGuildManager::GetInstance().SetRedpacketIdMax(kCUnionRepacket.m_idx);
		}
	}
	return true;
}

int32_t CGuild::CancelApply(Player& player)
{
	TGuildApplyMap::iterator it = apply_map_.find(player.GetPlayerId());
	if ( it == apply_map_.end() )
	{
		return ::common::ERR_GUILD_NOT_IN_APPLY;
	}
	apply_map_.erase(it);
	return ::common::SUCCEED;
}

CGuildMember* CGuild::GetViceChairman()
{
	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
	{
		CGuildMember& guildmember = it->second;
		if ( guildmember.title() == E_GUILD_TITLE_VICE_CHAIRMAN )
		{
			return &guildmember;
		}
	}
	return NULL;
}

void CGuild::GuildSave()
{
	Json::Value guild_data;
	SaveToJson(guild_data);
	Json::Value db_request;
	db_request["guild_data"] = guild_data;
	std::string db_str = JsonWriter(db_request);
	send_2_db(id_g2d_save_guild_request, db_str, 0);

	last_save_time_ = CUR_SEC;
}

void CGuild::SendMailToGuild(int32_t mail_type, Json::Value& itemlist, Json::Value& param, Json::Value& money)
{
	for (TGuildMemberMap::iterator it = member_map_.begin(); it !=  member_map_.end(); ++it )
	{
		CGuildMember& member = it->second;
		
		CMailModule::GetInstance().SendMailByPlayerId(member.player_id(), mail_type, itemlist, param, money);
	}
}

//-------------------------------------------------------------------------------
void CGuild::SendChatMessageToGuild(uint32_t playerId, uint32_t type,
	uint32_t destId, const char* pContant, Player& pMy, uint32_t shareType)
{
	_safe_guard_begin;

	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
	{
		CGuildMember& member = it->second;

		Player * _tmp_p = CSceneLogic::GetInstance().GetPlayerByPlayerID(member.player_id());
		if (nullptr != _tmp_p)
		{
			_tmp_p->PushChatMessageToClient(type, pContant
				, pMy.GetPlayerId()
				, pMy.GetAccount()
				, pMy.GetHeroId()
				, pMy.GetVip()
				, pMy.GetName()
				, 0
				, shareType);
		}
	}

	_safe_guard_end;
}

void CGuild::SendChatMessageToGuild(uint32_t playerId, uint32_t type,
	uint32_t destId, const char* pContant, Player& pMy
	, const char* pGvcId, double dGvcTime, const char* pGvcPart)
{
	_safe_guard_begin;

	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
	{
		CGuildMember& member = it->second;

		Player * _tmp_p = CSceneLogic::GetInstance().GetPlayerByPlayerID(member.player_id());
		if (nullptr != _tmp_p)
		{
			_tmp_p->PushChatMessageToClient(type, pContant
				, pMy.GetPlayerId()
				, pMy.GetAccount()
				, pMy.GetHeroId()
				, pMy.GetVip()
				, pMy.GetName()
				, pGvcId
				, dGvcTime
				, pGvcPart);
		}
	}

	_safe_guard_end;
}

void CGuild::BossDieNotify()
{
	Json::Value notify;
	notify["msgid"] = union_boss_die_notify;
	std::string sendstr = JsonWriter(notify);
	SendToGuild(sendstr, union_boss_die_notify);
}

void CGuild::onBossEnd(bool bossdie)
{
	const CUnionBossCfg& boss_cfg = CTPLManager::GetInstance().GetUnionBossInfo();
	const CUnionBossLv* boss_lv_cfg = boss_cfg.Getbossinfo(guild_boss_.boss_lv());
	if (boss_lv_cfg == NULL)
	{
		LOG_ERROR("default", "boss lv cfg is null [%d]", guild_boss_.boss_lv());
		return;
	}
	//参与奖励
	{
		Json::Value itemlist;
		boss_lv_cfg->award_partake().GetMailJsonItem(itemlist);
//		std::string itemlist_str = JsonWriter(itemlist);

		for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
		{
			// 发放击杀奖励
			CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(it->first);
			if (playerinfo != NULL)
			{
// 				std::string title = "公会boss参与奖励.";
// 				std::string content = "恭喜您参与击杀公会boss，获得奖励.";
// 				MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
// 					LUA_SendMail, it->first, playerinfo->get_name().c_str(), title.c_str(), content.c_str(), itemlist_str.c_str());
				Json::Value money;
				Json::Value param;
				CMailModule::GetInstance().SendMailByPlayerId(it->first, EMAIL_UNIONBOSS_JOIN, itemlist, param, money);
			}
		}
	}
	//排名奖励
	{
		Json::Value itemlist;
		boss_lv_cfg->award_num1().GetMailJsonItem(itemlist);
//		std::string itemlist_str = JsonWriter(itemlist);

		int32_t playerId = guild_boss_.GetFirstRankPlayer();
		CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(playerId);
		if (playerinfo != NULL)
		{
// 			std::string title = "公会boss参与奖励";
// 			std::string content = "恭喜您参与击杀公会boss，获得奖励.";
// 			MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
// 				LUA_SendMail, playerId, playerinfo->get_name().c_str(), title.c_str(), content.c_str(), itemlist_str.c_str());
			Json::Value money;
			Json::Value param;
			CMailModule::GetInstance().SendMailByPlayerId(playerId, EMAIL_UNIONBOSS_RANK, itemlist, param, money);
		}
	}
}

void CGuild::KillBoss(int32_t playerId)
{
	const CUnionBossCfg& boss_cfg = CTPLManager::GetInstance().GetUnionBossInfo();
	const CUnionBossLv* boss_lv_cfg = boss_cfg.Getbossinfo(guild_boss_.boss_lv());
	if (boss_lv_cfg == NULL)
	{
		LOG_ERROR("default", "boss lv cfg is null [%d]", guild_boss_.boss_lv());
		return;
	}
	Json::Value itemlist;
	boss_lv_cfg->award_kill().GetMailJsonItem(itemlist);
//	std::string itemlist_str = JsonWriter(itemlist);
	// 发放击杀奖励
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(playerId);
	if (playerinfo != NULL)
	{
// 		std::string title = "公会boss击杀奖励";
// 		std::string content = "恭喜您全服击杀公会boss，获得奖励.";
// 		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
// 			LUA_SendMail, playerId, playerinfo->get_name().c_str(), title.c_str(), content.c_str(), itemlist_str.c_str());
		Json::Value money;
		Json::Value param;
		CMailModule::GetInstance().SendMailByPlayerId(playerId, EMAIL_UNIONBOSS_KILL, itemlist, param, money);
	}
}

int32_t CGuild::CanApply(int32_t player_id)
{
	if (IsApplyListFull())
	{
		return ::common::ERR_GUILD_APPLY_FULL;
	}
	TGuildApplyMap::iterator it = apply_map_.find(player_id);
	if (it != apply_map_.end())
	{
		return ::common::ERR_UNION_REPLY_OFFER_THIS;
	}
	return ::common::SUCCEED;
}

int32_t CGuild::CanJoin(CPlayerInfo& playerinfo, EGuildTitle guild_title)
{
	if (IsGuildFull())
	{
		return ::common::ERR_IS_LIMIT_MEMBERS;
	}
	return ::common::SUCCEED;
}

bool CGuild::IsGuildFull()
{
	return (int32_t)member_map_.size() >= GetMaxMember();
}

bool CGuild::IsApplyListFull()
{
	return apply_map_.size() >= MAX_APPLY_NUM;
}

int32_t CGuild::JoinGuild(CPlayerInfo& playerinfo, int32_t title)
{
	CGuildMember member;
	member.set_player_id(playerinfo.get_playerId());
	member.set_join_time(CUR_SEC);
	member.set_title(title);
	member_map_.insert(TGuildMemberMap::value_type(playerinfo.get_playerId(), member));
	return ::common::SUCCEED;
}

//获取酒品列表
std::unordered_map<int32_t, CUnionAlcohol> CGuild::GetAlcohols()
{
	const CUnionLvCfg* union_cfg = CTPLManager::GetInstance().GetUnionCfgByLevel(guild_level_);
	Json::Value alcohol_ids = union_cfg->alcohol_ID;

	std::unordered_map<int32_t, CUnionAlcohol> alcohols_map;
	for (int32_t i = 0; i < alcohol_ids.size(); ++i)
	{
		int32_t alcohol_id = alcohol_ids[i].asInt();
		const CUnionAlcohol *union_alcohol = CTPLManager::GetInstance().GetUnionAlcoholByID(alcohol_id);

		if (union_alcohol == NULL) {
			continue;
		}
		alcohols_map.insert(std::make_pair(alcohol_id, *union_alcohol));
	}

	return alcohols_map;
}

bool CGuild::UpdateRedpacket(CUnionRepacket kCUnionRepacket)
{
	m_unionRepacket_map_[kCUnionRepacket.m_idx] = kCUnionRepacket;
	return true;
}

void CGuild::FillRedpacketList(int32_t player_id, int32_t type, Json::Value& redpacketlist_json)
{
	uint32_t now_time = CUR_SEC;
	for (TCUnionRepacketMap::iterator it = m_unionRepacket_map_.begin(); it != m_unionRepacket_map_.end();)
	{
		CUnionRepacket& guild_repacket = it->second;

		UnionRedpacketInfo kUnionRedpacketInfo = UnionRedpacketTableMgrPtr->GetUnionRedpacketInfoById(guild_repacket.m_tId);

		if (type < EGuildRepacketClientType::ERepacketClientSystem || type > EGuildRepacketClientType::ERepacketClientHistory)
		{
			return;
		}
		// 历史红包过期
		if (now_time > guild_repacket.m_sendTime + kUnionRedpacketInfo.m_continuedTime + GUILD_REDPACKET_DELETE_TIME)
		{
			it = m_unionRepacket_map_.erase(it);
		}
		else
		{
			// 系统红包
			if (type == EGuildRepacketClientType::ERepacketClientSystem && (now_time > guild_repacket.m_sendTime + kUnionRedpacketInfo.m_continuedTime || kUnionRedpacketInfo.m_type == EGuildRepacketType::ERepacketPlayer))
			{
				++it;
				continue;
			}
			// 历史红包
			if (type == EGuildRepacketClientType::ERepacketClientHistory && now_time < guild_repacket.m_sendTime + kUnionRedpacketInfo.m_continuedTime)
			{
				++it;
				continue;
			}
			// 玩家红包
			if (type == EGuildRepacketClientType::ERepacketClientPlayer && (now_time > guild_repacket.m_sendTime + kUnionRedpacketInfo.m_continuedTime || kUnionRedpacketInfo.m_type != EGuildRepacketType::ERepacketPlayer))
			{
				++it;
				continue;
			}

			Json::Value oneRepacket;
			oneRepacket["id"] = guild_repacket.m_idx;
			oneRepacket["tId"] = guild_repacket.m_tId;
			oneRepacket["getCount"] = guild_repacket.m_getCount;
			oneRepacket["name"] = guild_repacket.m_name;
			oneRepacket["state"] = EGuildRepacketState::ERepacketNotGet;
			TUnionRepacketInfoMap::iterator list_it = guild_repacket.m_list.find(player_id);
			if (list_it != guild_repacket.m_list.end())
			{
				oneRepacket["state"] = EGuildRepacketState::ERepacketGet;
			}
			else
			{
				// 已抢光
				if (guild_repacket.m_list.size() >= kUnionRedpacketInfo.m_allCount)
				{
					oneRepacket["state"] = EGuildRepacketState::ERepacketClear;
				}
				else
				{
					if (type == EGuildRepacketClientType::ERepacketClientHistory)
					{
						oneRepacket["state"] = EGuildRepacketState::ERepacketOverTime;
					}
				}
			}

			if (now_time > guild_repacket.m_sendTime + kUnionRedpacketInfo.m_continuedTime)
			{
				oneRepacket["remainTime"] = guild_repacket.m_sendTime + kUnionRedpacketInfo.m_continuedTime + GUILD_REDPACKET_DELETE_TIME - now_time;
			}
			else
			{
				oneRepacket["remainTime"] = guild_repacket.m_sendTime + kUnionRedpacketInfo.m_continuedTime - now_time;
			}

			redpacketlist_json.append(oneRepacket);

			++it;
		}
	}
}

CUnionRepacket CGuild::GetUnionRepacketById(int32_t id)
{
	CUnionRepacket kCUnionRepacket;
	TCUnionRepacketMap::iterator it = m_unionRepacket_map_.find(id);
	if (it != m_unionRepacket_map_.end())
	{
		return it->second;
	}

	return kCUnionRepacket;
}

bool CGuild::ExsitGetRepacketRewardByPlayerId(int32_t id, int32_t playerid)
{
	//TUnionRepacketInfoMap::iterator itr = NULL;
	TUnionRepacketInfoMap::iterator itr = m_unionRepacket_map_[id].m_list.find(playerid);
	if (itr == m_unionRepacket_map_[id].m_list.end())
	{
		return false;
	}

	return true;
}

void CGuild::SendRechargeRedpacket()
{
	UnionRedpacketInfo kUnionRedpacketInfo;
	if (!UnionRedpacketTableMgrPtr->GetUnionRedpacketInfoBySystem(ESystemGuildRedPacketType::E_RECHARGE, kUnionRedpacketInfo))
	{
		return;
	}

	int32_t idx = CGuildManager::GetInstance().GetRedpacketIdMax() + 1;
	CGuildManager::GetInstance().SetRedpacketIdMax(idx);

	CUnionRepacket kCUnionRepacket;
	kCUnionRepacket.m_idx = idx;
	kCUnionRepacket.m_unionId = guild_id_;
	kCUnionRepacket.m_name = kUnionRedpacketInfo.m_name;
	kCUnionRepacket.m_sendTime = CUR_SEC;
	kCUnionRepacket.m_tId = kUnionRedpacketInfo.m_id;
	kCUnionRepacket.m_remainItemCount = kUnionRedpacketInfo.m_redPacketItemCount;
	kCUnionRepacket.m_getCount = 0;
	kCUnionRepacket.m_createTime = CUR_SEC;
	UpdateRedpacket(kCUnionRepacket);
}

CGuildMember* CGuild::GetMember(int32_t role_id)
{
	TGuildMemberMap::iterator it = member_map_.find(role_id);
	if (it == member_map_.end())
	{
		return NULL;
	}
	return &it->second;
}

int32_t CGuild::GetMaxMember() const
{
	const CUnionLvCfg* union_cfg = CTPLManager::GetInstance().GetUnionCfgByLevel(guild_level_);
	if ( union_cfg == NULL )
	{
		return 50;
	}
	return union_cfg->upper_limit;
}

void CGuild::Dissolve()
{
	is_dissovled_ = true;
	dissovled_time_ = CUR_SEC;
	Json::Value playerlist;
	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
	{
		CGuildMember& guild_member = it->second;
		// 玩家在线，将C++中数据改变，redis中数据改变
		// 玩家不在线，将redis中数据改变
		// 给每个玩家发送邮件
//		player_union_data_change(guild_member.player_id(), 0, "", 0, E_LEAVE_GUILD);
		CUnionModule::GetInstance().OnPlayerUnionDataChange(guild_member.player_id(), 0, "", 0, E_LEAVE_GUILD);

		Json::Value player;
		CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(guild_member.player_id());
		if ( playerinfo != NULL )
		{
			player["playerId"] = guild_member.player_id();
			player["name"] = playerinfo->get_name();
			playerlist.append(player);
		}
	}
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(chairman_player_id_);
	if ( playerinfo != NULL )
	{
		Json::Value table_param;
		table_param["playerId"] = chairman_player_id_;
		table_param["name"] = playerinfo->get_name();
		table_param["playerlist"] = playerlist;

		std::string str = JsonWriter(table_param);
		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
			LUA_UnionEvent, ELua_DisbandUnion, str.c_str());
	}
	 
	GuildSave();
}


void CGuild::GuildInfo2Json(Json::Value& guild_info)
{
	guild_info["ui"] = guild_id_;
	guild_info["un"] = guild_name_;
	guild_info["mo"] = declaration_;
	guild_info["ic"] = guild_icon_;
	guild_info["ci"] = chairman_player_id_;
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(chairman_player_id_);
	if (playerinfo != NULL)
	{
		guild_info["cn"] = playerinfo->get_name();
	}
	guild_info["lv"] = guild_level_;
	guild_info["ep"] = guild_exp_;
	guild_info["ct"] = create_time_;
	guild_info["cp"] = (int32_t)member_map_.size();
	guild_info["dn"] = today_donation_;
	guild_info["mp"] = GetMaxMember();// 最大人数
	guild_info["minlv"] = min_limit_lv_;
	guild_info["rank"] = CGuildManager::GetInstance().GetGuildRank(guild_id_);
	guild_info["autojoin"] = auto_join_;
}

void CGuild::SendToGuild(std::string& msg, int32_t msgid)
{
	for (TGuildMemberMap::iterator it = member_map_.begin(); it != member_map_.end(); ++it)
	{
		CGuildMember& guildMember = it->second;
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(guildMember.player_id());
		if (player == NULL)
		{
			continue;
		}
		player->SendToClient(&msg, msgid);
	}
}

void CGuildRankTimer::TimerActive()
{
	CGuildManager::GetInstance().UpdateGuildRank();
	TimerStart();
}

CGuildManager::CGuildManager() : guild_id_max_(0)
{
	update_sec_ = 0;
	redpacket_id_max_ = 0;
	boss_first_kill_.clear();
}

CGuildManager::~CGuildManager()
{
	for (TGuildMap::iterator it = guild_map_.begin(); it != guild_map_.end(); ++it)
	{
		delete it->second;
	}
	guild_map_.clear();
	guild_name_map_.clear();
	guild_rank_vec_.clear();
}

bool CGuildManager::Initialize()
{
	guild_id_max_ = 0;
	redpacket_id_max_ = 0;
	// 公会排行一分钟排序一次
	guild_rank_timer_.TimerInit(60 * 1000);
	guild_rank_timer_.TimerStart();
	if (false == LoadGuildDB())
	{
		return false;
	}
	return true;
}

bool CGuildManager::Finalize()
{
	for (TGuildMap::iterator it = guild_map_.begin(); it != guild_map_.end(); ++it)
	{
		delete it->second;
	}
	guild_map_.clear();
	guild_name_map_.clear();
	return true;
}


bool CGuildManager::LoadGuildDB()
{
	std::string host = GameHostManager::GetInstance().GetGameDBIP();
	std::string prot = GameHostManager::GetInstance().GetGameDBProt();
	std::string user = GameHostManager::GetInstance().GetGameDBUser();
	std::string pwd = GameHostManager::GetInstance().GetGameDBPwd();
	std::string dbname = GameHostManager::GetInstance().GetGameDBName();
	sql::Connection conn;
	if (conn.Init(host, prot, user, pwd, dbname) == false)
	{
		LOG_WARN("default","init db conn : %s:%s:%s:%s:%s failed", host.c_str(), prot.c_str(), user.c_str(), pwd.c_str(), dbname.c_str());
		return false;
	}
	sql::ResultSet result_set;
	std::string sql = "SELECT guildid,guildname,createid,chairid,icon, guildlv, guildexp, createtime,dissovled,dissovledtime,apply,member,exdata,redpacket FROM tb_base_guild ";
	sql.append(" where dissovled = 0; ");
	sql::ResultSet* res = conn.ExecuteQuery(sql.c_str(), result_set);
	if (res == NULL)
	{
		LOG_WARN("default","Load gate_guild failed");
		return false;
	}
	while (res->next() == true)
	{
		Json::Value guild_data;
		guild_data.clear();
		guild_data["guildid"] = res->getInt("guildid");
		guild_data["guildname"] = res->getStringStr("guildname");
		guild_data["createid"] = res->getInt("createid");
		guild_data["chairid"] = res->getInt("chairid");
		guild_data["icon"] = res->getStringStr("icon");
		guild_data["guildlv"] = res->getInt("guildlv");
		guild_data["guildexp"] = res->getInt("guildexp");
		guild_data["createtime"] = res->getInt("createtime");
		guild_data["dissovled"] = res->getInt("dissovled");
		guild_data["dissovledtime"] = res->getInt("dissovledtime");
		guild_data["apply"] = res->getStringStr("apply");
		guild_data["member"] = res->getStringStr("member");
		guild_data["exdata"] = res->getStringStr("exdata");
		guild_data["redpacket"] = res->getStringStr("redpacket");
		CreateGuild(guild_data);
	}
	result_set.close();
	conn.Close();
	// 检测非法的仙盟
	CheckInValidCampGuild();
	UpdateGuildRank();

	return true;
}


CGuild* CGuildManager::GetGuildByID(int32_t guild_id)
{
	TGuildMap::iterator it = guild_map_.find(guild_id);
	if (it != guild_map_.end())
	{
		return it->second;
	}
	return NULL;
}

CGuild* CGuildManager::GetGuildByName(const std::string& guild_name)
{
	TGuildNameMap::iterator it = guild_name_map_.find(guild_name);
	if (it != guild_name_map_.end())
	{
		return it->second;
	}
	return NULL;
}

CGuild* CGuildManager::CreateGuild(const std::string& guild_name, const std::string& image_id_, CPlayerInfo& player, const std::string& dec, int32_t minlv, int32_t auto_join)
{
	CGuild* guild_ptr = new CGuild();
	if (NULL == guild_ptr)
	{
		return NULL;
	}
	int32_t guildid = ++guild_id_max_;
	int32_t areaid = GameHostManager::GetInstance().GetServerAreaId();
	guildid = (areaid << 20) | guildid;
	guild_ptr->set_guild_id(guildid);
	guild_ptr->set_icon(image_id_);
	guild_ptr->set_name(guild_name);
	guild_ptr->set_chairman_player(player.get_playerId());
	guild_ptr->set_create_player(player.get_playerId());
	guild_ptr->set_guilde_lv(1);
	guild_ptr->set_guild_exp(0);
	guild_ptr->set_create_time(CUR_SEC);
	guild_ptr->set_dec(dec);
	guild_ptr->set_minlv(minlv);
	guild_ptr->set_auto_join(auto_join);
	AddGuild(*guild_ptr);
	JoinGuild(player, *guild_ptr, E_GUILD_TITLE_CHAIRMAN);

	if (CActivityModule::GetInstance().IsActivityOpen(2))
	{
		guild_ptr->GetGuildBoss().StartBoss();
	}
	return guild_ptr;
}

CGuild* CGuildManager::CreateGuild(const Json::Value& guild_data)
{
	if (guild_data["dissovled"].asInt())
	{
		RefreshGuildIDMax(guild_data["guildid"].asInt());
		return NULL;
	}
	CGuild* guild_ptr = new CGuild();
	if (NULL == guild_ptr)
	{
		return NULL;
	}
	guild_ptr->LoadFromJson(guild_data);
	AddGuild(*guild_ptr);
	return guild_ptr;
}

void CGuildManager::DissolveGuild(int32_t guild_id)
{
	TGuildMap::iterator it = guild_map_.find(guild_id);
	if (it == guild_map_.end())
	{
		return;
	}
	CGuild* guild_ptr = it->second;
	if (NULL == guild_ptr)
	{
		guild_map_.erase(it);
		return;
	}
	guild_ptr->Dissolve();

	guild_name_map_.erase(guild_ptr->get_name());
	guild_map_.erase(it);
	TGuildRankVec::iterator rank_it = std::find(guild_rank_vec_.begin(), guild_rank_vec_.end(), guild_id);
	if (rank_it != guild_rank_vec_.end())
	{
		guild_rank_vec_.erase(rank_it);
	}
	delete guild_ptr;
}


void CGuildManager::UpdateGuildRank()
{
	std::sort(guild_rank_vec_.begin(), guild_rank_vec_.end(), SGuildComp());
}

int32_t CGuildManager::ApplyGuild(int32_t playerid, CGuild& guild)
{
	int32_t ret_code = guild.CanApply(playerid);
	if (::common::SUCCEED != ret_code)
	{
		return ret_code;
	}
	ret_code = guild.AddApply(playerid);
	return ret_code;
}

int32_t CGuildManager::ReplyApply(Player& player, int32_t dest_id, bool agree)
{
	int32_t guild_id = player.GetUnionId();
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(guild_id);
	if (NULL == guild)
	{
		return ::common::ERR_NOT_JOINED_UNION;
	}
	CGuildMember* member = guild->GetMember(player.GetPlayerId());
	if (NULL == member)
	{
		return ::common::ERR_NOT_JOINED_UNION;
	}

	CGuild::TGuildApplyMap& apply_map = guild->apply_map();
	CGuild::TGuildApplyMap::iterator it = apply_map.find(dest_id);
	if (it == apply_map.end())
	{
		return ::common::ERR_GUILD_NO_APPLY;
	}

	guild->DeleteApply(dest_id);
	if (false == agree)
	{
		return ::common::SUCCEED;
	}

	if (guild->IsGuildFull())
	{
		return ::common::ERR_IS_LIMIT_MEMBERS;
	}
	CPlayerInfo* apply_player = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(dest_id);
	if (NULL == apply_player)
	{
		return ::common::ERR_GUILD_ROLE_NOT_FIND;
	}
	if (0 != apply_player->get_union_id())
	{
		return ::common::ERR_JOINED_OTHER_UNION;
	}

	if (apply_player->PlayerGuild().leave_guild_time() != 0 && apply_player->PlayerGuild().GetJoinCDLimitTime() > CUR_SEC)
	{
		return ::common::ERR_GUILD_OTHER_JOIN_UNION_CD;
	}
	if ( apply_player->get_level() < guild->minlimitlv() )
	{
		return ::common::ERR_GUILD_OTHER_JOIN_LV_LESS;
	}

	return JoinGuild(*apply_player, *guild, E_GUILD_TITLE_MEMBER);
}

int32_t CGuildManager::JoinGuild(CPlayerInfo& playerinfo, CGuild& guild, EGuildTitle title)
{
	int32_t ret_code = guild.CanJoin(playerinfo, title);
	if (::common::SUCCEED != ret_code)
	{
		return ret_code;
	}
	ret_code = guild.JoinGuild(playerinfo, title);

// 	for (TGuildMap::iterator it = guild_map_.begin(); it != guild_map_.end(); ++it)
// 	{
// 		CGuild* guild_apply = it->second;
// 		if (NULL == guild_apply || guild_apply->InApplyList(playerinfo.get_playerId()) == false)
// 		{
// 			continue;
// 		}
// 		guild_apply->DeleteApply(playerinfo.get_playerId());
// 	}
	int32_t changetype = 0;
	if (title == E_GUILD_TITLE_CHAIRMAN)
	{
		changetype = E_CREATE_GUILD;
	}
	else
	{
		changetype = E_JOIN_GUILD;
	}
	CUnionModule::GetInstance().OnPlayerUnionDataChange(playerinfo.get_playerId(), guild.get_guild_id(), guild.get_name(), title, changetype);
	return ret_code;
}

int32_t CGuildManager::LeaveGuild(CGuild& guild, int32_t playerid)
{
	guild.LeaveGuild(playerid);
	if (guild.member_map().empty())
	{
		CGuildManager::GetInstance().DissolveGuild(guild.get_guild_id());
	}
//	player_union_data_change(playerid, 0, "", 0, E_LEAVE_GUILD);
	CUnionModule::GetInstance().OnPlayerUnionDataChange(playerid, 0, "", 0, E_LEAVE_GUILD);
	return ::common::SUCCEED;
}

int32_t CGuildManager::KickoutGuild(CGuild& guild, int32_t playerid, int32_t dest_id)
{
	CGuildMember* member = guild.GetMember(playerid);
	if (NULL == member)
	{
		return ::common::ERR_NOT_JOINED_UNION;
	}
	CGuildMember* dest_member = guild.GetMember(dest_id);
	if ( dest_member == NULL )
	{
		return ::common::ERR_NOT_YOUR_UNION_MEMBER;
	}
	if (member->title() <= dest_member->title())
	{
		return ::common::ERR_NOT_ENOUGH_UNION_SCOPE;
	}
	guild.LeaveGuild(dest_id);
//	player_union_data_change(playerid, 0, "", 0, E_LEAVE_GUILD);
	CUnionModule::GetInstance().OnPlayerUnionDataChange(dest_id, 0, "", 0, E_LEAVE_GUILD);
	return ::common::SUCCEED;
}

void CGuildManager::AddGuild(CGuild& guild)
{
	guild_map_.insert(TGuildMap::value_type(guild.get_guild_id(), &guild));
	guild_name_map_.insert(TGuildNameMap::value_type(guild.get_name(), &guild));
	guild_rank_vec_.push_back(guild.get_guild_id());
	RefreshGuildIDMax(guild.get_guild_id());
}

int32_t CGuildManager::RefreshGuildIDMax(int32_t guild_id)
{
	int32_t real_guildid = guild_id & 0x000FFFFF;
	guild_id_max_ = guild_id_max_ > real_guildid ? guild_id_max_ : real_guildid;
	return guild_id_max_;
}

void CGuildManager::CheckInValidCampGuild()
{

}

void CGuildManager::OnNewDay()
{
	for (TGuildMap::iterator it = guild_map_.begin(); it != guild_map_.end(); ++it)
	{
		CGuild* guild = it->second;
		if (NULL == guild)
		{
			continue;
		}
		guild->OnNewDay();
	}
}

void CGuildManager::OnNewWeek()
{
	for (TGuildMap::iterator it = guild_map_.begin(); it != guild_map_.end(); ++it)
	{
		CGuild* guild = it->second;
		if (NULL == guild)
		{
			continue;
		}
		guild->OnNewWeek();
	}
}

int32_t CGuildManager::GuildBossCall(int32_t role_id, int32_t boss_id)
{
	return 0;
}

int32_t CGuildManager::GuildBossEnter(int32_t role_id)
{
	return 0;
}

void CGuildManager::TickUpdate()
{
	if (update_sec_ == CUR_SEC)
	{
		return;
	}
	update_sec_ = CUR_SEC;

	for (TGuildMap::iterator iter = guild_map_.begin(); iter != guild_map_.end(); ++iter)
	{
		CGuild* guild = iter->second;
		if (NULL == guild)
		{
			continue;
		}
		//guild->Update( );
	}

	SaveGuild();
}

void CGuildManager::SaveGuild()
{
	EServiceStatus service_statuss = GameServer::GetInstance().GetServiceStatus();
	// 只有在正常运行和准备停服中才有保存;
	if (service_statuss != SERVICE_WAITTING_EXIT && service_statuss != SERVICE_ISRUNNING)
	{
		return;
	}

	int32_t guild_update_count = 0;

	int32_t save_delta = 60;
	int32_t filter_num = CUR_SEC % save_delta;

	for (TGuildMap::iterator iter = guild_map_.begin(); iter != guild_map_.end(); ++iter)
	{
		int32_t guild_id = iter->first;
		CGuild* guild = GetGuildByID(guild_id);

		if (guild == NULL) continue;

		// 游戏运行中，保存策略是根据当前秒数取模来保存
		if (service_statuss == SERVICE_ISRUNNING) {
			if (guild->get_guild_id() % save_delta != filter_num) {
				continue;
			}
		}
		else if (service_statuss == SERVICE_WAITTING_EXIT) {
			if (exit_saved_guild_.find(guild_id) != exit_saved_guild_.end()) {
				continue;
			}
			else {
				exit_saved_guild_.insert(guild_id);
			}
		}

		guild->GuildSave();
		guild->set_last_save_time(CUR_SEC);

		guild_update_count++;
		if (service_statuss == SERVICE_WAITTING_EXIT) {
			if (guild_update_count > 60) break;
		}
	}
	if (guild_update_count > 0)
	{
		LOG_INFO("default","save guild count %d", guild_update_count);
	}
}


void CGuildManager::ReGuildLevel()
{

}

int32_t CGuildManager::CheckKickoutGuildConflict(const CGuild& guild)
{

	return ::common::SUCCEED;
}

void CGuildManager::FillGuildToJson(Json::Value& item, int32_t start, int32_t count)
{
	int32_t cur_index = 0;
	int32_t cur_count = 0;
	for (TGuildRankVec::iterator it = guild_rank_vec_.begin(); it != guild_rank_vec_.end(); ++it)
	{
		CGuild* guild = GetGuildByID(*it);
		if (NULL == guild) {
			continue;
		}
		if (cur_index < start)
		{
			cur_index++;
			continue;
		}
		Json::Value guild_info;
		guild_info.clear();
		guild->GuildInfo2Json(guild_info);
		item.append(guild_info);
		cur_count++;
		if (cur_count >= count)
		{
			break;
		}
	}
}

void CGuildManager::GetPlayerApplyList(Json::Value& auj, int32_t playerid)
{
	for (TGuildMap::iterator iter = guild_map_.begin(); iter != guild_map_.end(); ++iter) {
		CGuild* guild = iter->second;
		if (NULL == guild) {
			continue;
		}
		if (guild->InApplyList(playerid))
		{
			auj.append(guild->get_guild_id());
		}
	}
}

void CGuildManager::GuildChangeName(std::string& oldname, CGuild& guild)
{
	TGuildNameMap::iterator it = guild_name_map_.find(oldname);
	if ( it != guild_name_map_.end())
	{
		guild_name_map_.erase(it);
	}
	guild_name_map_.insert(TGuildNameMap::value_type(guild.get_name(), &guild));
}

int32_t CGuildManager::GetGuildRank(int32_t guildid)
{
	for (int32_t i = 0; i < guild_rank_vec_.size();  ++i )
	{
		if (guild_rank_vec_[i] == guildid)
		{
			return i + 1;
		}
	}
	return 0;
}

void CGuildManager::GetUnionInfoById(int32_t guildid, std::string& unioninfo)
{
	unioninfo.clear();
	CGuild* guild = GetGuildByID(guildid);
	if (guild == NULL )
	{
		return;
	}
	Json::Value union_json;
	guild->GuildInfo2Json(union_json);
	unioninfo = JsonWriter(union_json);
}

void CGuildManager::GetUnionApplyList(int32_t guildid, std::string& applylist)
{
	applylist.clear();
	CGuild* guild = GetGuildByID(guildid);
	if (guild == NULL)
	{
		return;
	}
	Json::Value apply_list;
	guild->FillApplyList(apply_list);
	applylist = JsonWriter(apply_list);
}

void CGuildManager::GuildBossNotify()
{
	for (std::set<int32_t>::iterator it = guild_boss_enter_.begin(); it != guild_boss_enter_.end(); ++it )
	{
		CGuild* guild = GetGuildByID(*it);
		if (guild == NULL )
		{
			continue;
		}

		Json::Value notify;
		notify["msgid"] = union_boss_info_notify;
		notify["maxhp"] = (double)guild->GetGuildBoss().boss_maxhp();
		notify["curhp"] = (double)guild->GetGuildBoss().boss_curhp();
		notify["bossid"] = guild->GetGuildBoss().boss_id();
		notify["level"] = guild->GetGuildBoss().boss_lv();
		Json::Value ranklist;
		guild->GetGuildBoss().CalcDamageRank();
		guild->GetGuildBoss().FillDamageRank(ranklist);
		notify["ranklist"] = ranklist;
		std::string sendstr = JsonWriter(notify);
		guild->SendToGuild(sendstr, union_boss_info_notify);
	}
}

void CGuildManager::GuildBossStart()
{
	guild_boss_enter_.clear();
	for (TGuildMap::iterator it = guild_map_.begin(); it != guild_map_.end(); ++it)
	{
		CGuild* guild = it->second;
		if (guild == NULL)
		{
			continue;
		}

		guild->GetGuildBoss().StartBoss();

		Json::Value notify;
		notify["start"] = 1;
		notify["msgid"] = union_boss_start_notify;
		std::string sendstr = JsonWriter(notify);
		guild->SendToGuild(sendstr, union_boss_start_notify);
	}
}

void CGuildManager::GuildEnterBoss(CGuild& guild)
{
	guild_boss_enter_.insert(guild.get_guild_id());
}

void CGuildManager::CalcFirstKill(CGuild& guild, int32_t bossid, int32_t bosslv, int32_t playerid)
{
	auto it = boss_first_kill_.find(bossid);
	if ( it != boss_first_kill_.end() )
	{
		return;
	}

	boss_first_kill_.insert(std::make_pair(bossid, playerid));

	const CUnionBossCfg& boss_cfg = CTPLManager::GetInstance().GetUnionBossInfo();
	const CUnionBossLv* boss_lv_cfg = boss_cfg.Getbossinfo(bosslv);
	if ( boss_lv_cfg == NULL )
	{
		LOG_ERROR("default", "boss lv cfg is null [%d]", bosslv);
		return;
	}
	Json::Value itemlist;
	boss_lv_cfg->award_firstblood().GetMailJsonItem(itemlist);
//	std::string itemlist_str = JsonWriter(itemlist);
	// 发放首杀奖励
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(playerid);
	if ( playerinfo != NULL )
	{
// 		std::string title = "首杀奖励";
// 		std::string content = "恭喜您全服首杀公会boss，获得奖励.";
// 		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
// 			LUA_SendMail, playerid, playerinfo->get_name().c_str(), title.c_str(), content.c_str(), itemlist_str.c_str());
		Json::Value money;
		Json::Value param;
		CMailModule::GetInstance().SendMailByPlayerId(playerid, EMAIL_UNIONBOSS_FIRST_KILL, itemlist, param, money);
	}
	Json::Value tmp;
	Json::Value param;
	Json::Value param1;
	Json::Value param2;
	if ( playerinfo != NULL )
	{
		param1 = playerinfo->get_name();
	}
	MonsterInfo* bossinfo = MonsterCacheData::GetInstance().GetData(bossid);
	if (bossinfo != NULL)
	{
		param2 = bossinfo->mName;
	}
	else
	{
		LOG_ERROR("default", "start boss err MonsterInfo[%d] is null", bossid);
	}
	param.append(param1);
	param.append(param2);
	guild.SendMailToGuild(EMAIL_UNIONBOSS_FIRST_KILL_NOTICE, tmp, param, tmp);
	SaveGuildData();
}

void CGuildManager::GuildBossEnd()
{
	for (std::set<int32_t>::iterator it = guild_boss_enter_.begin(); it != guild_boss_enter_.end(); ++it)
	{
		CGuild* guild = GetGuildByID(*it);
		if (guild == NULL)
		{
			continue;
		}
		Json::Value notify;
		notify["start"] = 0;
		notify["msgid"] = union_boss_start_notify;
		std::string sendstr = JsonWriter(notify);
		guild->SendToGuild(sendstr, union_boss_start_notify);

		guild->onBossEnd(false);
	}
}

void CGuildManager::LoadGuildData(Json::Value& guilddata)
{
	Json::Value first_kill = guilddata["firstkill"];
	LoadGuildFirstKill(first_kill);
}

void CGuildManager::LoadGuildFirstKill(Json::Value& firstKill)
{
	boss_first_kill_.clear();
	for (int32_t i = 0; i < firstKill.size(); ++i )
	{
		Json::Value onefirst = firstKill[i];
		int32_t bossid = onefirst["bossid"].asInt();
		int32_t playerid = onefirst["playerid"].asInt();

		boss_first_kill_.insert(std::make_pair(bossid, playerid));
	}
}

void CGuildManager::InitGuildData()
{
	boss_first_kill_.clear();
}

void CGuildManager::SaveGuildData()
{
	Json::Value request;
	request["msgid"] = union_data_save_request;
	Json::Value guilddata;
	Json::Value firstkill;
	SaveGuildFirstKill(firstkill);
	guilddata["firstkill"] = firstkill;
	request["uniondata"] = guilddata;
	std::string sendstr = JsonWriter(request);
	send_2_db(union_data_save_request, sendstr, 0);
}

void CGuildManager::SaveGuildFirstKill(Json::Value& firstKill)
{
	for (auto it = boss_first_kill_.begin(); it != boss_first_kill_.end(); ++it )
	{
		Json::Value onefirst;
		onefirst["bossid"] = (int32_t)it->first;
		onefirst["playerid"] = (int32_t)it->second;
		firstKill.append(onefirst);
	}
}

int32_t CGuildManager::GetGuildBossActivityID()
{
	const CUnionLvCfg* unionlv_cfg = CTPLManager::GetInstance().GetUnionCfgByLevel(1);
	if ( unionlv_cfg == NULL )
	{
		return 0;
	}
	return unionlv_cfg->guild_boss_actid;
}

int32_t CGuildManager::autoApply(CGuild& guild, int32_t destid)
{
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(destid);
	if ( playerinfo == NULL )
	{
		return ::common::ERR_GUILD_ROLE_NOT_FIND;
	}

	int32_t ret_code = JoinGuild(*playerinfo, guild, E_GUILD_TITLE_MEMBER);
	if ( ret_code != ::common::SUCCEED )
	{
		return ret_code;
	}
	// 执行后续lua逻辑
	if (ret_code == ::common::SUCCEED)
	{
		guild.AddGuildLog(guild.get_chairman_player(), destid, ELog_Join);
		Json::Value table_param;
		table_param["playerId"] = destid;
		table_param["unionId"] = guild.get_guild_id();
		std::string str = JsonWriter(table_param);
		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_UnionManagerScript,
			LUA_UnionEvent, ELua_JoinUnion, str.c_str());
	}
	return ret_code;
}

void CGuildManager::ApplyListNotify(CGuild& guild, int32_t playerid)
{
	Json::Value notify;
	notify["msgid"] = union_apply_list_notify;
	Json::Value item;
	guild.FillApplyList(item);
	notify["item"] = item;
	
	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerid);
	if ( player != NULL )
	{
		player->SendToClient(notify, union_apply_list_notify);
	}
}

// 酒品消耗
int32_t CGuildAlcoholLogic::ReduceCurrency(Player& player, const CUnionAlcohol& alcohol)
{
	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		return ::common::ERR_NOT_JOINED_UNION;
	}

	const CUnionLvCfg* cfg = CTPLManager::GetInstance().GetUnionCfgByLevel(guild->get_guilde_lv());
	CGuildMember* member = guild->GetMember(player.GetPlayerId());
	if (member == NULL)
	{
		return ::common::ERR_NOT_JOINED_UNION;

	}

	int32_t alcohol_count = member->get_alcohol_count();
	int32_t min_alcohol_count = (cfg->expense)[0].begin_id;
	if (alcohol_count <= min_alcohol_count) {
		return ::common::SUCCEED;
	}

	size_t count = (sizeof(cfg->expense) / sizeof(cfg->expense[0]));
	int32_t coin = 0;
	int32_t coin_count = 0;
	for (int32_t i = 0; i < count; ++i )
	{
		const CItemExpense item_cfg = (cfg->expense)[i];

		if (alcohol_count >= item_cfg.begin_id && alcohol_count <= item_cfg.end_id) {
			coin = item_cfg.itemid;
			coin_count = item_cfg.count;
			break;
		}

	}

	if (coin == 114000200) {
		player.SetCurrency(Fixed1024::CURRENCY_DIAMOND, coin_count);
		player.SetPlayerSomeInfoToRedisDB("diamond", coin_count);
	}
	if (coin == 114000100) {
		player.SetCurrency(Fixed1024::CURRENCY_GOLD, coin_count);
		player.SetPlayerSomeInfoToRedisDB("gold", coin_count);
	}

	return ::common::SUCCEED;
}

// 使用酒品
int32_t CGuildAlcoholLogic::SaveAlcoholMembers(Player& player, const CUnionAlcohol& alcohol,Json::Value& target)
{

	CGuild* guild = CGuildManager::GetInstance().GetGuildByID(player.GetUnionId());
	if (guild == NULL)
	{
		return ::common::ERR_NOT_JOINED_UNION;
	}

	CGuildMember* member = guild->GetMember(player.GetPlayerId());
	if (member == NULL)
	{
		return ::common::ERR_NOT_JOINED_UNION;

	}

	member->set_alcohol_id(alcohol.alcohol_id);
	member->set_alcohol_count(1, true);
	member->set_alcohol_expire(CUR_SEC);
	target["alcohol_count"] = member->get_alcohol_count();
	return ::common::SUCCEED;
}